package com.oldbook.manage.controller;

import com.oldbook.common.annotation.Log;
import com.oldbook.common.core.controller.BaseController;
import com.oldbook.common.core.domain.AjaxResult;
import com.oldbook.common.core.page.TableDataInfo;
import com.oldbook.common.enums.BusinessType;
import com.oldbook.common.exception.ServiceException;
import com.oldbook.manage.domain.Order;
import com.oldbook.manage.domain.OrderRequest;
import com.oldbook.manage.domain.vo.OrderVO;
import com.oldbook.manage.service.ICartService;
import com.oldbook.manage.service.IOrderService;
import com.oldbook.manage.service.ITextbookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 教材订单Controller
 *
 * @author Exiaoke
 * @date 2025-02-17
 */
@RestController
@RequestMapping("/manage/order")
@Api(tags = "教材订单管理")
@Slf4j
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICartService cartService;

    @Autowired
    private ITextbookService textbookService;

/**
 * 查询教材订单列表
 */
@PreAuthorize("@ss.hasPermi('manage:order:list')")
@GetMapping("/list")
@ApiOperation("查询教材订单列表")
    public TableDataInfo list(@ApiParam("教材订单对象") OrderVO order) {
        startPage();
        List<OrderVO> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }
    /**
     * 减库存
     */

    @PreAuthorize("@ss.hasPermi('manage:order:list')&& @creditCheck.isCreditValid()")
    @PostMapping("/confirm")
    @ApiOperation("新增教材订单")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult  confirmOrder(@RequestBody OrderRequest request) {
        try {
            // 1. 扣减库存
            log.debug("前端提交的数据[{}]", request);
            textbookService.deductStock(request.getTextbookId(), request.getQuantity());
            log.debug("");

            // 2. 生成订单记录
            orderService.createOrder(request.getStudentId(), request.getTextbookId(), request.getQuantity());

            // 3. 清空购物车（省略具体实现）
            cartService.clearCart(request.getTextbookId());

            //返回成功信息和状态码
            return AjaxResult.success("订单创建成功");
        } catch (ServiceException e) {
            // 捕获并返回错误信息
            return AjaxResult.error(e.getMessage());

        }

    }

    /**
     * 获取教材订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:order:query')")
    @GetMapping(value = "/{orderId}")
    @ApiOperation("获取教材订单详细信息")
    public AjaxResult getInfo(@PathVariable("orderId") @ApiParam("orderId的值") Long orderId) {



        return success(orderService.selectOrderByOrderId(orderId));
    }

    /**
     * 新增教材订单
     */
    @PreAuthorize("@ss.hasPermi('manage:order:add')")
    @Log(title = "教材订单", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增教材订单")
    public AjaxResult add(@RequestBody @ApiParam("要添加的教材订单对象") Order order) {

        return toAjax(orderService.insertOrder(order));
    }

    /**
     * 修改教材订单
     */
    @PreAuthorize("@ss.hasPermi('manage:order:edit')")
    @Log(title = "教材订单", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改教材订单")
    public AjaxResult edit(@RequestBody @ApiParam("要修改的教材订单对象") Order order) {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除教材订单
     */
    @PreAuthorize("@ss.hasPermi('manage:order:remove')")
    @Log(title = "教材订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    @ApiOperation("删除教材订单")
    public AjaxResult remove(@PathVariable @ApiParam("要删除的orderId数组") Long[] orderIds) {
        return toAjax(orderService.deleteOrderByOrderIds(orderIds));
    }
    /**
     * 根据学号查询教材订单列表
     */
    
    @PreAuthorize("@ss.hasPermi('manage:order:list')")
    @GetMapping("/listByStudentId/{studentId}")
    @Log(title = "教材订单", businessType = BusinessType.OTHER)
    @ApiOperation("根据学号查询教材订单列表")
    public TableDataInfo ByStudentId(@PathVariable @ApiParam("学号") String studentId) {

        //开启分页
        startPage();
        List<OrderVO> orderListByStudentId = orderService.getOrderListByStudentId(studentId);
        //返回分页数据
        return getDataTable(orderListByStudentId);
    }
}